package org.openstack.service.instance;

import org.openstack.api.instance.InstanceService;
import org.openstack4j.api.compute.ComputeService;
import org.openstack4j.model.compute.Server;
import org.openstack4j.openstack.compute.internal.ComputeServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiyun on 2017/8/28.
 */
public class InstanceServiceImpl implements InstanceService {

    private static ComputeService service = new ComputeServiceImpl();

    /**
     * 获取所有的虚拟机实例
     *
     * @return 虚拟机实例列表
     */
    @Override
    public List<? extends Server> getAllInstance() {
        return service.servers().listAll(true);
    }

    /**
     * 获取指定计算节点上所有的虚拟机实例
     * TODO: 优化查询性能
     *
     * @param HypervisorId 计算节点物理机ID
     * @return 虚拟机实例列表
     */
    @Override
    public List<? extends Server> getInstancesByHypervisorID(String HypervisorId) {
        List<Server> results = new ArrayList<>();
        for (Server s : getAllInstance()) {
            if (s.getHostId().equals(HypervisorId)) {
                results.add(s);
            }
        }
        return results;
    }

    /**
     * 获取指定计算节点上所有的虚拟机实例
     * TODO: 优化查询性能
     *
     * @param HypervisorHostname 计算节点主机名
     * @return 虚拟机实例列表
     */
    @Override
    public List<? extends Server> getInstancesByHypervisorHostname(String HypervisorHostname) {
        List<Server> results = new ArrayList<>();
        for (Server s : getAllInstance()) {
            if (s.getHypervisorHostname().equals(HypervisorHostname)) {
                results.add(s);
            }
        }
        return results;
    }
}
